package service

import (
	"encoding/json"
	"errors"
	"wwgin/common"
	"wwgin/model"
	"wwgin/module/redis_factory"
)

type IpService struct {
}

//获取一个ip地址的信息
func (i *IpService) GetOne(ip string) (map[string]interface{}, error) {
	cache, err2 := i.GetCache(ip)
	if err2 == nil {
		return cache, err2
	}
	IpInfoModel := model.IpInfo{}
	ipInfo, err := IpInfoModel.GetOne(ip)

	//数据库没有找到,去第三方接口请求
	if err != nil {
		info, err := ArkIp.GetInfo(ip)
		if err != nil {
			return i.Format(ipInfo), err
		}
		//添加到数据库,并返回
		add, res := IpInfoModel.Add(
			ip,
			info.IP地址解析实体信息["待查询IP地址解析实体信息"]["国家"],
			info.IP地址解析实体信息["待查询IP地址解析实体信息"]["省份"],
			info.IP地址解析实体信息["待查询IP地址解析实体信息"]["城市"],
			info.IP地址解析实体信息["待查询IP地址解析实体信息"]["区域"],
			info.IP地址解析实体信息["待查询IP地址解析实体信息"]["ISP运营商"],
			info.IP地址解析实体信息["待查询IP地址解析实体信息"]["GPS"],
			info.IP地址解析实体信息["待查询IP地址解析实体信息"]["国家行政编码"],
		)
		if res != nil {
			return i.Format(add), errors.New("数据添加失败")
		}
		i.SetCache(ip, i.Format(add))
		return i.Format(add), err
	}
	i.SetCache(ip, i.Format(ipInfo))
	return i.Format(ipInfo), err
}

//格式化返回数据
func (i *IpService) Format(info model.IpInfo) map[string]interface{} {
	var ret = map[string]interface{}{}
	var other map[string]string
	err := json.Unmarshal([]byte(info.Other), &other)
	if err != nil {
		return ret
	}
	ret["ip"] = common.InetNtoA(int64(info.Ip))
	ret["country"] = info.Country
	ret["province"] = info.Province
	ret["city"] = info.City
	ret["area"] = info.Area
	ret["isp"] = info.Isp
	ret["other"] = other
	return ret
}

func (i *IpService) SetCache(ip string, info map[string]interface{}) bool {
	var cacheKey = "ip_detail_info_go:" + ip
	redisClient := redis_factory.GetOneRedisClient("def")
	defer redisClient.ReleaseOneRedisClient() //释放
	marshal, err := json.Marshal(info)
	if err != nil {
		return false
	}
	_, err = redisClient.Execute("set", cacheKey, string(marshal), "ex", 86400)
	if err != nil {
		return false
	}
	return true
}

func (i *IpService) GetCache(ip string) (ret map[string]interface{}, err error) {
	var cacheKey = "ip_detail_info_go:" + ip
	redisClient := redis_factory.GetOneRedisClient("def")
	defer redisClient.ReleaseOneRedisClient() //释放
	res, err := redisClient.String(redisClient.Execute("get", cacheKey))
	if err != nil {
		return
	}

	if res == "" || res == "{}" {
		err = errors.New("没有找到对应的缓存数据")
		return
	}

	err = json.Unmarshal([]byte(res), &ret)
	if err != nil {
		return
	}
	return
}
